package com.qf.controller;

import com.qf.vo.ResultVo;
import com.qf.vo.VoteWaterFlow;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Date;
import java.util.concurrent.TimeUnit;

@RestController
public class VoteController {

    @Autowired
    private RedisTemplate redisTemplate;

    @PostMapping("/vote")
    public ResultVo vote(String phone,String name){

        // 检查该手机号是否在一分钟之内投过票
        String key1 = "vote:phone:"+phone;
//        Object o = redisTemplate.opsForValue().get(key1);
//        if (o!=null){
//            throw new RuntimeException("请不要在1分钟之内连续投票！");
//        }

        Boolean flag = redisTemplate.hasKey(key1);
        if (!flag){
            throw new RuntimeException("请不要在1分钟之内连续投票！");
        }

        //1. 向redis的zset中对name进行加分操作
       String key2 = "vote:phone";
        Double result = redisTemplate.opsForZSet()
                .incrementScore(key2, name, 1);

        //2. 成功投票后，需要在redis中记录该手机号
        redisTemplate.opsForValue()
                .set(key1,new Date(),60, TimeUnit.SECONDS);

        //3. 记录投票的流水信息 (手机号、候选人、投票时间)
        String key3 = "vote:waterflow";
        redisTemplate.opsForList()
                .rightPush(key3,new VoteWaterFlow(phone,name,new Date()));


        return new ResultVo(1,"ok",result);

    }

}
